package cn.jiangjiesheng.bootstrap.commons.utils;

import cn.jiangjiesheng.bootstrap.commons.constants.SdkClientConstant;
import cn.jiangjiesheng.bootstrap.commons.entity.LoginSessionInfo;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;

/**
 * Cookie工具类<br>
 * Created by dev@jiangjiesheng.cn on 20-03-11.
 */
public class CookieUtil {
    public static String getValue(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            Optional<String> optional = Arrays.stream(cookies).filter(cookie -> key.equals(cookie.getName())).map(cookie -> cookie.getValue()).findFirst();
            return null != optional && optional.isPresent() ? optional.get() : null;
        }
        return null;
    }


    /**
     * 获取sessionId<br>
     * 优先获取id_token，没有则使用原来的方法
     *
     * @param httpServletRequest
     * @returnk
     */
    public static String getSessionId(HttpServletRequest httpServletRequest) {
        String sessionId = CookieUtil.getValue(httpServletRequest, SdkClientConstant.SESSIONID_NEW);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(sessionId)) {
            return sessionId;
        }

        return CookieUtil.getValue(httpServletRequest, SdkClientConstant.PHPSESSID);
    }

    public static String getJLoginSessionId(HttpServletRequest httpServletRequest) {
        String jLoginSessionId = CookieUtil.getValue(httpServletRequest, SdkClientConstant.JLOGINSESSIONID);

        return jLoginSessionId;
    }


    /**
     * 获取登录session new,推荐使用这种方式
     *
     * @param request
     * @return
     */
    public static LoginSessionInfo getLoginSessionInfo(HttpServletRequest request) {
        LoginSessionInfo session = new LoginSessionInfo();

        session.setSessionId(getSessionId(request));
        session.setJLoginSessionId(getJLoginSessionId(request));

        return session;
    }

}
